<template>
  <div class="echarts-container">
    <!-- 导航按钮 -->
    <div class="nav_btn">
      <div v-for="n, index in thatTime" :key="n.value">
        <el-button :type="index == NavActive ? 'primary' : ''" @click="changeTab(index)" v-show="!n.disabled">
          {{ n.name }}
        </el-button>
      </div>
    </div>
    
    <!-- 图表容器 -->
    <div ref="chart" class="chart-wrapper"></div>
  </div>
</template>

<script>
import { getHourlyVisitData } from '@/api/chenlong.js'
import * as echarts from "echarts";
export default {
  name: 'EChartsChart',
  props: {
    corpId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chart: null, // 图表实例
      thatTime: [
        { name: '访问人数', value: 1, disabled: false },
        { name: '打开次数', value: 2, disabled: false },
        { name: '访问页面', value: 3, disabled: true }
      ],
      NavActive: 0,
      hourlyVisitData: []
    }
  },
  computed:{
    xAxisData(){
      if (this.hourlyVisitData && this.hourlyVisitData.length > 0) {
        return this.hourlyVisitData.map(item => item.hour + ':00')
      }
      return ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00']
    },
    visitCountData(){ //访问人数数据
      const data = [
        {name: '今日', data: this.hourlyVisitData.map(item => item.todayUserCount)},
        {name: '1天前', data: this.hourlyVisitData.map(item => item.yesterdayUserCount)},
        {name: '7天前', data: this.hourlyVisitData.map(item => item.sevenDaysAgoUserCount)}
      ]
      return data
    },
    openCountData(){  //打开次数数据
      const data = [
        {name: '今日', data: this.hourlyVisitData.map(item => item.todayCountOpen)},
        {name: '1天前', data: this.hourlyVisitData.map(item => item.yesterdayCountOpen)},
        {name: '7天前', data: this.hourlyVisitData.map(item => item.sevenDaysAgoCountOpen)}
      ]
      return data
    },
    pageCountData(){ //访问页面数据
      //return this.hourlyVisitData.map(item => item.pageCount)
    },

  },
  watch: {
    corpId: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.gentCurrentData()  // corpId变化时更新数据
        }
      },
      // immediate: true
    }
  },
  mounted() {
    // 初始化图表
    this.initChart()
    this.gentCurrentData()  //访问实时数据
    // 监听窗口大小变化，自适应图表
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 销毁图表实例，释放资源
    if (this.chart) {
      this.chart.dispose()
    }
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    changeTab(index) {
      if (this.NavActive == index) return
      this.NavActive = index
      // 根据选择的指标更新图表
      this.updateChart()
    },
    
    updateChart() {
      // 根据NavActive更新图表数据
      if (this.chart) {
        // 这里可以根据NavActive更新图表配置
        this.chart.setOption(this.getChartOptions())
      }
    },
    
    getChartOptions() {
      // 根据NavActive返回不同的图表配置
      const baseOptions = {
        tooltip: {
          trigger: 'axis'
        },
        color: ['#00cf8a', '#6184fb', '#faa52d'], // 全局颜色：对应"今日""1天前""7天前"
        legend: {
          data: ['今日', '1天前','7天前'],
          bottom: '0',
          icon: 'circle', // 图标形状为圆形
          itemWidth: 8, 
          show:true,  // 圆点大小
          itemHeight: 8   // 圆点大小（与宽度一致保持圆形）
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '12%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.xAxisData
        },
        yAxis: {
          type: 'value'
        },
        series: this.getSeriesData()
      }
      return baseOptions
    },
    
    getSeriesData() {
      // 根据NavActive返回不同的数据系列
      const series = []
      
      if (this.hourlyVisitData && this.hourlyVisitData.length > 0) {
        // 根据NavActive选择不同的数据源
        let currentData = []
        switch(this.NavActive) {
          case 0: // 访问人数
            currentData = this.visitCountData
            break
          case 1: // 打开次数
            currentData = this.openCountData
            break
          case 2: // 访问页面
            currentData = this.pageCountData || []
            break
          default:
            currentData = this.visitCountData
        }
        
        // 定义颜色配置
        const colors = ['#00cf8a', '#6184fb', '#faa52d']
        
        // 为每个数据系列创建对应的series配置
        currentData.forEach((item, index) => {
          const color = colors[index] || '#00cf8a'
          
          // 定义渐变阴影
          const gradient = {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: color + '60' }, // 添加透明度
              { offset: 1, color: color + '00' }   // 完全透明
            ]
          }
          
          series.push({
            name: item.name,
            type: 'line',
            data: item.data || [],
            smooth: true,
            showSymbol: false, // 去掉数据点
            areaStyle: {
              color: gradient // 添加渐变阴影
            },
            lineStyle: {
              width: 2, // 线条宽度
              color: color // 线条颜色
            }
          })
        })
      } else {
        // 没有数据时显示空图表
        const defaultSeries = [
          { name: '今日', data: [] },
          { name: '1天前', data: [] },
          { name: '7天前', data: [] }
        ]
        
        const colors = ['#00cf8a', '#6184fb', '#faa52d']
        
        defaultSeries.forEach((item, index) => {
          const color = colors[index] || '#00cf8a'
          
          series.push({
            name: item.name,
            type: 'line',
            data: item.data,
            smooth: true,
            showSymbol: false,
            areaStyle: {
              color: color + '60'
            },
            lineStyle: {
              width: 2,
              color: color
            }
          })
        })
      }
      
      return series
    },
   
   async gentCurrentData() { //访问实时数据
      const params = {
        corpId: this.corpId
      }
      const res = await getHourlyVisitData(params)
      if (res.code == 200) {
        this.hourlyVisitData = res.data.hourlyData
        this.$emit('updateTimeLineTime', res.data.updateTime)
      //  console.log(">>>", this.xAxisData);
        // 数据更新后重新渲染图表
        this.updateChart()
      }
    },
    initChart() {
      // 初始化图表实例
      this.chart = echarts.init(this.$refs.chart)
      
      // 定义绿色渐变阴影
      const greenGradient = {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [
          { offset: 0, color: 'rgba(129, 227, 153, 0.6)' }, // 淡绿色，透明度60%
          { offset: 1, color: 'rgba(129, 227, 153, 0)' }   // 完全透明
        ]
      };
      
      // 图表配置项
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        color: ['#00cf8a', '#6184fb', '#faa52d'], // 全局颜色：对应“今日”“1天前”“7天前”
        legend: {
          data: ['今日', '1天前','7天前'],
          bottom: '0',
          icon: 'circle', // 图标形状为圆形
          itemWidth: 8,   // 圆点大小
          itemHeight: 8   // 圆点大小（与宽度一致保持圆形）
        },
        grid: {
          top: '5%',
          left: '3%',
          right: '4%',
          bottom: '12%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.xAxisData
        },
        yAxis: {
          type: 'value'
        },
        series: this.getSeriesData()
      }
      
      // 设置图表配置项
      this.chart.setOption(option)
    },
    // 处理窗口大小变化
    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    }
  }
}
</script>

<style scoped lang="scss">
.echarts-container {
  width: 100%;
  padding: 20px;
}

.chart-wrapper {
  width: 100%;
  height: 300px; /* 必须设置高度，否则图表不显示 */
}

.nav_btn {
  width: 360px;
  display: flex;
  gap: 5%;
  //justify-content: space-between;
  flex-shrink: 0;
  margin-bottom: 16px;
}

.nav_btn .el-button {
  margin-right: 8px;
}
</style>
